﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.InformationManagement.Core.Support;
using Microsoft.SharePoint;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using System.IO;
using MS.InformationManagement.Core.TransactionsResponse;

namespace MS.InformationManagement.BLL.DeliveryForms
{
    public class DeliveryFormDocumentCreatorCommand : ICommandWithResponse
    {

        #region Constants

        const string DELIVERY_FORM_PATH = @"C:\Program Files\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\LAYOUTS\MS.InformationManagement.WP";

        #endregion

        #region Private Fields

        string _fileContent;
        string _fileName;

        #endregion

        #region Constructors

        public DeliveryFormDocumentCreatorCommand(string fileContent)
        {
            _fileContent = fileContent;
        }

        #endregion

        public ITransactionResponse Execute()
        {
            setFilePath();
            DeliveryFormCreationResponse response = new DeliveryFormCreationResponse();

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                createDocument();
                getNewDocument(response); 
            });

            return response;
        }

        private void getNewDocument(DeliveryFormCreationResponse response)
        {
            using (FileStream deliveryForm = new FileStream(_fileName, FileMode.Open, FileAccess.Read))
            {
                response.Result = true;
                byte[] fileBytes = new byte[deliveryForm.Length];
                deliveryForm.Read(fileBytes, 0, Convert.ToInt32(deliveryForm.Length));
                response.DeliveryContent = fileBytes;
                response.DocumentName = Path.GetFileName(_fileName);
            }
            File.Delete(_fileName);
        }

        private void createDocument()
        {
            using (Document document = new Document(iTextSharp.text.PageSize.LETTER_LANDSCAPE.Rotate()))
            {
                document.SetMargins(10, 10, 10, 10);
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(_fileName, FileMode.Create));
                document.Open();
                StringReader sr = new StringReader(_fileContent);
                XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, sr);
            }
        }


        public void Undo()
        {
            if (File.Exists(_fileName))
                File.Delete(_fileName);
        }

        #region private methods

        private void setFilePath()
        {
            string documentId = Guid.NewGuid().ToString();
            _fileName = DELIVERY_FORM_PATH + "\\" + documentId + ".pdf";
        }

        #endregion

    }
}
